package cn.edu.nuc.ssm.controller;

import cn.edu.nuc.ssm.dto.BbsTopicAndUsername;
import cn.edu.nuc.ssm.dto.Result;
import cn.edu.nuc.ssm.entity.*;
import cn.edu.nuc.ssm.service.*;
import cn.edu.nuc.ssm.util.IPTimeStamp;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/5/2.
 */
@Controller
@RequestMapping("/user")
public class UsercenterController{


    @Autowired
    private BbsSectionService bbsSectionService;

    @Autowired
    private UserService userService;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BorrowMoneyManagerService borrowMoneyManagerService;

    @Autowired
    private DefaultTransferService defaultTransferService;
    @Autowired
    private JizhangService jizhangService;
    @Autowired
    private BbsTopicService bbsTopicService;


    @RequestMapping( value = "/index",method = RequestMethod.GET )
    public String index(HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        return "front/user/user_center";
    }
    @RequestMapping(value = "/intro",method = RequestMethod.GET)
    public String intro(Model model,HttpSession session){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        User findbyId = userService.findbyId(user.getId());
        model.addAttribute("user",findbyId);

        return "front/user/user_intro";
    }

    @RequestMapping(value = "/caiwuindex",method = RequestMethod.GET)
    public String caiwutypeindex(HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        List<Category> categorieszhi = userService.findbyzhiCategory(user.getId());
        List<Category> categoriesshou = userService.findbyshouruCategory(user.getId());
        model.addAttribute("zhilist",categorieszhi);
        model.addAttribute("shoulist",categoriesshou);

        return "front/user/user_caiwutype";
    }

    @RequestMapping(value = "/saveuser",method = RequestMethod.POST)
    public String save(User user){

        userService.updateUserMessage(user);

        return "redirect:/user/intro";
    }

    @RequestMapping(value = "toaddshoutype",method = RequestMethod.GET)
    public String toaddshoutype(){


        return "front/user/user_caiwutype_addshou";
    }

    @RequestMapping(value = "toaddzhitype",method = RequestMethod.GET)
    public String toaddzhitype(){


        return "front/user/user_caiwutype_addzhi";
    }

    @RequestMapping(value = "addzhitype",method = RequestMethod.POST)
    public String addzhitype(Category category,HttpSession session){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        category.setCategoryBelong(1);
        category.setUid(user.getId());
        userService.saveInsertCategory(category);

        return "redirect:/user/caiwuindex";
    }
    @RequestMapping(value = "addshoutype",method = RequestMethod.POST)
    public String addshouType(Category category,HttpSession session){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        category.setCategoryBelong(2);
        category.setUid(user.getId());
        userService.saveInsertCategory(category);

        return "redirect:/user/caiwuindex";
    }

    @RequestMapping(value = "toupdatezhitype",method = RequestMethod.GET)
    public String toupdatezhiType(Category category,HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        Category category1 = categoryService.findByid(category.getId());
        model.addAttribute("category",category1);

        return "front/user/user_caiwutype_updatezhi";
    }

    @RequestMapping(value = "updatezhitype",method = RequestMethod.POST)
    public String updatezhiType(Category category,HttpSession session,Model model){

        categoryService.updateSelective(category);

        return "redirect:/user/caiwuindex";
    }

    @RequestMapping(value = "toupdateshoutype",method = RequestMethod.GET)
    public String toupdateshouType(Category category,HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }
        Category category1 = categoryService.findByid(category.getId());
        model.addAttribute("category",category1);

        return "front/user/user_caiwutype_updateshou";
    }

    @RequestMapping(value = "updateshoutype",method = RequestMethod.POST)
    public String updateshouType(Category category,HttpSession session,Model model){

        categoryService.updateSelective(category);
        return "redirect:/user/caiwuindex";
    }

    @RequestMapping(value = "delete",method = RequestMethod.GET)
    public String deleteCategory(Integer uid,Integer id){

        categoryService.deleteCategoryAndRefece(uid,id);
        return "redirect:/user/caiwuindex";
    }

    //添加
    @RequestMapping(value = "/toupload",method=RequestMethod.GET)
    public String toupdate(HttpSession session, Model model){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        String pic = userService.findpicByid(user.getId());
        model.addAttribute("pic",pic);

        return "front/user/user_upload";
    }

    //添加
    @RequestMapping(value = "/upload",method=RequestMethod.POST)
    public String upload(User user,@RequestParam("file")MultipartFile file,HttpServletRequest request) throws IOException {


        if (user.getId()==null){

            throw new RuntimeException();
        }

        String realPath = request.getSession().getServletContext()
                .getRealPath("/upload");

        File pathFile = new File(realPath);
        if (!pathFile.exists()) {

            pathFile.mkdir();
        }
        IPTimeStamp ipTimeStamp = new IPTimeStamp();
        //获得新文件的名字
        String timeStamp = ipTimeStamp.getTimeStamp();

        //获得上传文件的后缀
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        //并新文件的名称
        String newFilename = timeStamp + "." + ext;

        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, newFilename));

        user.setPic(newFilename);


        userService.updatePic(user);

        return "redirect:/user/toupload";
    }

    @RequestMapping(value = "/jiedaiweihuan",method=RequestMethod.GET)
    public String jiedai(HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        List<BorrowMoneyManager> moneyManagerList = borrowMoneyManagerService.listWeihuanMoney(user.getId(), 0);
        model.addAttribute("moneyManagerList",moneyManagerList);

        return "front/user/user_jiedai";
    }

    @RequestMapping(value = "/jiedaiyihuan",method=RequestMethod.GET)
    public String jiedaihuan(HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        List<BorrowMoneyManager> moneyManagerList = borrowMoneyManagerService.listWeihuanMoney(user.getId(), 1);
        model.addAttribute("moneyManagerList",moneyManagerList);

        return "front/user/user_jiedai_huan";
    }

    @RequestMapping(value = "/huanqie",method=RequestMethod.GET)
    public String jiedaihuanqie(HttpSession session,Model model,Integer id){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        borrowMoneyManagerService.updateStatus(id);

        BorrowMoneyManager borrowMoneyManager = borrowMoneyManagerService.findbyId(id);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());

        AccountTransfer defaultTranfer = defaultTransferService.findDefaultTranfer(user.getId());
        defaultTranfer.setDetail(borrowMoneyManager.getDetail());
        defaultTranfer.setTransferDate(format);
        defaultTranfer.setTransferMoney(borrowMoneyManager.getMoney());

        jizhangService.huankuanMoney(defaultTranfer);

        return "redirect:/user/jiedaiweihuan";
    }

    @RequestMapping(value = "bbsmodify",method = RequestMethod.GET)
    public String bbsModify(HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:/front/tologin";
        }

        List<BbsTopic> bbsTopicList = bbsTopicService.findbyUid(user.getId());

        model.addAttribute("bbsList",bbsTopicList);


        return "front/user/user_bbs_modify";
    }

    @RequestMapping(value = "bbsOpenTopic",method = RequestMethod.GET)
    public String openBbsTopic(BbsTopic bbsTopic,Model model){

        BbsTopic bbsTopicfd = bbsTopicService.findbyId(bbsTopic.getId());

        model.addAttribute("bbsTopic",bbsTopicfd);

        List<String> allSectionType = bbsSectionService.findAllSectionType();
        List<BbsSection> list = bbsSectionService.find();
        model.addAttribute("allsection",allSectionType);
        model.addAttribute("subsection",list);

        List<BbsTopicAndUsername> topicAndUsername = bbsTopicService.findTopicAndUsername(bbsTopicfd.getSid());

        model.addAttribute("topiclist",topicAndUsername);

        BbsSection bbsSection = bbsSectionService.findbyId(bbsTopicfd.getSid());

        model.addAttribute("bbsSection",bbsSection);

        List<String> sectionType = bbsSectionService.findSectionType();
        model.addAttribute("sectionlist",sectionType);

        BbsSection section = bbsSectionService.findbyId(bbsTopicfd.getSid());
        model.addAttribute("section",section);

        return "front/bbs/bbs_modify_topic";
    }

    @ResponseBody
    @RequestMapping(value = "/updatetopic",method = RequestMethod.POST)
    public Result<BbsTopic> writeTopic(@RequestBody BbsTopic bbsTopic, Model model){

//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = new Date();
//        String nowTime = simpleDateFormat.format(date);
//        bbsTopic.setTime(nowTime);

        int i = 0;
        try {
            i = bbsTopicService.updateBbsTopic(bbsTopic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (i<=0){
            return new Result<BbsTopic>("error",null);
        }
        return new Result<BbsTopic>("success",bbsTopic);
    }
}
